﻿using HAF.Core.SysUtils;
using HAF.Core.Utils;
using HAF.LogUtility;
using Iptv.UploadResourceItem.Helper;
using MediaTransfer.Helper;
using MediaTransfer.Impl;
using MediaTransfer.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MediaTransfer
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
        }

        #region 消息输出
        private void ShowPopTips(string message)
        {
            MessageBox.Show(message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        int _msgLen = 0;

        private void ShowClear()
        {
            txtMsg.Clear();
        }

        private void ShowMessage(string msg)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action<string>(ShowMessage), msg);
            }
            else
            {
                if (_msgLen >= 300)
                {
                    txtMsg.Clear();
                    //txtMessages.Text = "";
                    _msgLen = 0;
                }
                LogHelper.WriteDebugLog(msg);

                txtMsg.Text = txtMsg.Text + (DateTime.Now.ToString() + " " + msg + "\r\n");
                txtMsg.SelectionStart = txtMsg.Text.Length;
                txtMsg.ScrollToCaret();

                _msgLen++;

            }
        }

        #endregion 消息输出

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void SetButtonState(bool isShow)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action<bool>(SetButtonState), isShow);
            }
            else
            {
                btnSend.Enabled = isShow;
            }
                
        }

        string localPrefix1 = "\\\\sctv.x410\\Publish";
        string localPrefix2 = "\\\\sctv.x410\\Media03\\Media";
        string targetPrefix1 = "\\\\172.25.8.165\\icms\\vsg\\unicom";
        string targetPrefix2 = "\\\\172.25.8.185\\icms2\\vsg\\mobileold";

        private void btnSend_Click(object sender, EventArgs e)
        {
            ShowClear();
            ShowMessage("任务启动");
            
            //获取分布式ID（雪花ID）
            long tt = SnowflakeWorker.Instance.GetId();
            ShowMessage(tt.ToString());

            //创建接收工作项
            IWorkItem runJob = new BaseWorker()
            {
                ID = SnowflakeWorker.Instance.GetId(),
                Tag = "10010",
                //TaskID = inParams.OrderID,  //工作项编号和工单本地编号一致
                Name = "Test01",
                Priority = 10,
                Model = 1,
                RedoTimes = 1,
                WorkID = "Test001",
                WorkItems = new string[] { "1","B"},
                WorkJson = "",
                Statu = 0,
                WorkType = 1,
                AllowRemoteExec = false
            };

            var newObj1 = ObjHelper.DeepCopyByReflect<IWorkItem>(runJob);
            if (newObj1 != null)
            {
                newObj1.TaskID = Guid.NewGuid().ToString();
                newObj1.Statu = 9;
                ShowMessage(newObj1.TaskID);
                ShowMessage(runJob.TaskID);
                newObj1.ExecItem();
            }
            var newObj = ObjHelper.Clone<IWorkItem>(runJob);
            if (newObj != null)
            {
                newObj.TaskID = Guid.NewGuid().ToString();
                newObj.Statu = 9;
                ShowMessage(newObj.TaskID);
                newObj.ExecItem();
                ShowMessage(runJob.TaskID);
            }
            

            
            //SetButtonState(false);
            //string passage = cmbType.SelectedText;
            //if (string.IsNullOrEmpty(passage))
            //{
            //    passage = cmbType.SelectedIndex == 0 ? "LTICMS01" : "LTICMS06";
            //}
            //List<MediaTaskDto> mediaDatas = MediaDbHelper.GetInstance().GetTaskData(txtFName.Text, passage);
            //if (mediaDatas != null && mediaDatas.Count > 0)
            //{
            //    ShowMessage(string.Format("任务数量{0}", mediaDatas.Count));
            //    List<MediaTaskDto> tasks = new List<MediaTaskDto>();
            //    foreach (var item in mediaDatas)
            //    {
            //        ShowMessage(item.SrcPath);
            //        //Actual Education News Program Simpleset
            //        string srcFullPath = item.SrcPath.IndexOf("Multiset") >= 0 || item.SrcPath.IndexOf("Cartoon") >= 0 
            //            || item.SrcPath.IndexOf("Actual") >= 0 || item.SrcPath.IndexOf("Education") >= 0 || item.SrcPath.IndexOf("News") >= 0
            //            || item.SrcPath.IndexOf("Program") >= 0 || item.SrcPath.IndexOf("Simpleset") >= 0 ? Path.Combine(localPrefix2, item.SrcPath) : Path.Combine(localPrefix1, item.SrcPath);
            //        ShowMessage(srcFullPath);
            //        string destFullPath = Path.Combine(cmbType.SelectedIndex == 0 ? targetPrefix1: targetPrefix2, item.DestPath);
            //        if (CheckMediaSize(item.ID.ToString(), srcFullPath.Replace("/","\\"), destFullPath.Replace("/", "\\")))
            //        {
            //            ShowMessage(string.Format("文件[{0}]需要复制 {1}", item.FileName, destFullPath));
            //            tasks.Add(item);
            //        }

            //        //break;
            //    }
            //    ShowMessage(string.Format("待复制文件数量为{0}", tasks.Count));
            //    if (tasks.Count > 0)
            //    {
            //        Thread copyThread = new Thread(delegate () { CopyFilesThread(tasks); }) { Name = "copyThread", IsBackground = true};
            //        copyThread.Start();
            //    }
            //    else
            //    {
            //        SetButtonState(true);
            //    }
            //}
            //else
            //{
            //    SetButtonState(true);
            //    ShowMessage("未查找到数据");
            //}
        }

        private bool CheckMediaSize(string id, string srcPath, string destPath)
        {
            long srcSize = 0;
            if (File.Exists(srcPath))
            {
                FileInfo fileInfo = new FileInfo(srcPath);
                srcSize = fileInfo.Length;
                ShowMessage(string.Format("源文件{0}大小为{1}", srcPath, srcSize));
            }
            else
            {
                ShowMessage(string.Format("源文件{0}不存在", srcPath));
            }

            long destSize = 0;
            if (File.Exists(destPath))
            {
                FileInfo fileInfo = new FileInfo(destPath);
                destSize = fileInfo.Length;
                ShowMessage(string.Format("目标文件{0}大小为{1}", destPath, destSize));
            }
            else
            {
                ShowMessage(string.Format("目标文件{0}不存在", destPath));
            }

            if (srcSize == destSize)
            {
                ShowMessage("文件大小对比一致");
            }
            else
            {
                ShowMessage(string.Format("文件{0}大小对比异常 srcSize {1} destSize {2}", id, srcSize, destSize));
                return true;
            }
            return false;
        }

        bool waitResult = true;

        private void CopyFilesThread(List<MediaTaskDto> tasks)
        {
            int i = 1;
            foreach (var item in tasks)
            {
                waitResult = true;
                string srcFullPath = item.SrcPath.IndexOf("Multiset") >= 0 || item.SrcPath.IndexOf("Cartoon") >= 0
                        || item.SrcPath.IndexOf("Actual") >= 0 || item.SrcPath.IndexOf("Education") >= 0 || item.SrcPath.IndexOf("News") >= 0
                        || item.SrcPath.IndexOf("Program") >= 0 || item.SrcPath.IndexOf("Simpleset") >= 0 
                        ? Path.Combine(localPrefix2, item.SrcPath.Replace("/", "\\")) : Path.Combine(localPrefix1, item.SrcPath.Replace("/", "\\"));
                string destFullPath = Path.Combine(targetPrefix1, item.DestPath.Replace("/", "\\"));
                ShowMessage(string.Format("第{3}个任务[{2}] 文件{0}将拷贝到{1}", srcFullPath, destFullPath, item.FileName, i));

                //启动新的线程进行下载
                Thread runThread = new Thread(delegate () { CopyTask(item.ID.ToString(), srcFullPath, destFullPath); }) { Name = "runCopy", IsBackground = true };
                runThread.Start();
                //Task.Run(delegate () { CopyTask(item.ID.ToString(), srcFullPath, destFullPath); });
                i++;
                while (waitResult)
                {
                    ShowMessage(string.Format("等待任务{0}完成", item.ID.ToString()));
                    //等待1分钟
                    Thread.Sleep( 40 * 1000);
                }
            }
            ShowMessage("复制任务全部完成");
            
        }

        private void CopyTask(string id, string srcPath, string destPath)
        {
            using (MediaReplication mediaTwins = new MediaReplication(srcPath, destPath))
            {
                mediaTwins.LogOutName = id;
                mediaTwins.WriteConsoleMessageEvent = ShowMessage;
                mediaTwins.UploadTaskEndEvent = TaskEnd;
                mediaTwins.Run(id);
            }
        }

        private void TaskEnd(string id, bool stat, string message)
        {
            waitResult = false;
            SetButtonState(true);
            ShowMessage(string.Format("任务{0}完成 [{1}] {2}", id, stat, message));
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            cmbType.SelectedIndex = 0;
        }
    }
}
